package com.ocom.ugcapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ocom.common.constant.WxServiceUrl;
import com.ocom.common.entity.card.EntityXfAccountInfo;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.human.FeatureRequest;
import com.ocom.common.request.payconfig.SignatureUpdateRequest;
import com.ocom.common.request.payconfig.repairpay.GetRepairPayRecordListRequest;
import com.ocom.common.request.wx.UserAccessPageSetAccessRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.utils.bdface.GsonUtils;
import com.ocom.common.utils.bdface.HttpUtil;
import com.ocom.common.vo.AccessListVo;
import com.ocom.common.vo.PersonVo;
import com.ocom.common.vo.human.UserInfoYkmVo;
import com.ocom.common.vo.human.XfUserInfoVo;
import com.ocom.common.vo.ugcapi.GzhUserInfo;
import com.ocom.common.vo.webapi.BDFaceToken;
import com.ocom.redis.util.RedisUtil;
import com.ocom.ugcapi.client.*;
import com.ocom.ugcapi.config.RsaConfig;
import com.ocom.ugcapi.util.RSAHelper;
import com.ocom.ugcapi.vo.AddPersonVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2022/7/14
 **/
@Slf4j
@RestController
public class UserController {

	@Resource
	private RedisUtil redisUtil;

	@Autowired
	HumanClientService humanClientService;

	@Autowired
	MinioClientService minioClientService;

	@Autowired
	PayConfigClientService payConfigClientService;

	@Autowired
	MqSimpleClientService mqSimpleClientService;

	@Autowired
	AccessClientService accessClientService;

	 //公众号支付（/pay）
	@PostMapping(WxServiceUrl.URL_UserInfo)
	public Result UserInfo(@RequestBody Map<String,Object> map){
		GzhUserInfo user = (GzhUserInfo) map.get("userInfo");
//		String token = map.get("token").toString();
//		// 解析token
//		UserInfo user = null;
//		try {
//			Gson gson=new Gson();
//			String userStr  = RSAHelper.decipher(token, RsaConfig.privateKey);
//			user = gson.fromJson(userStr,UserInfo.class);
//		} catch (Exception e) {
//			log.info("Token解析异常 【{}】", e);
//			return ResultUtil.error(ResultEnum.Err_3042);
//		}
//		if(user.getComId()==266l){
//			return ResultUtil.error(ResultEnum.Err_502);
//		}

		Result result = humanClientService.getXfUserInfo(user.getComId(),user.getPId());
		if(result.getCode()!=200){
			return result;
		}
		XfUserInfoVo xfUserInfoVo = JSON.parseObject(JSON.toJSONString(result.getData()),XfUserInfoVo.class);
		if(xfUserInfoVo.getChargeBalance()==null){
			xfUserInfoVo.setChargeBalance(0);
		}
		if(xfUserInfoVo.getAccountSubsidyMoney()==null){
			xfUserInfoVo.setAccountSubsidyMoney(0);
		}
		xfUserInfoVo.setChargeBalance(xfUserInfoVo.getChargeBalance()+xfUserInfoVo.getAccountSubsidyMoney());
		return ResultUtil.success(xfUserInfoVo);
	}

	//修改密码
	@PostMapping(WxServiceUrl.URL_modifyPwd)
	public Result modifyPwd(@RequestBody Map<String,Object> map){
		GzhUserInfo user = (GzhUserInfo) map.get("userInfo");
//		String token = map.get("token").toString();
		String pwd = map.get("pwd").toString();
		if(CommonUtil.isNull(pwd)){
			return ResultUtil.error(ResultEnum.Err_3056);
		}

		List<String> errors = PasswordValidator.validatePassword(pwd);
		if (!errors.isEmpty()) {
			return ResultUtil.info(500,String.join(",",errors));
		}

//		List<Long> checkComId = new ArrayList<>();
//		Collections.addAll(checkComId, 75l, 77l, 89l, 106l, 113l, 123l, 126l, 127l, 130l, 133l,
//				526l, 584l, 619l, 622l, 626l, 633l, 656l, 670l, 671l, 678l, 680l, 706l,
//				651l,712l,673l,692l,748l,743l,713l,715l);
//
//		if(user.getComId()!=693 && !HandlePasswordUtil.isWeekPassword(pwd)){
//			return ResultUtil.error(ResultEnum.Err_3107);
//		}

//		// 解析token
//		UserInfo user = null;
//		try {
//			Gson gson=new Gson();
//			String userStr  = RSAHelper.decipher(token, RsaConfig.privateKey);
//			user = gson.fromJson(userStr,UserInfo.class);
//		} catch (Exception e) {
//			log.info("Token解析异常 【{}】", e);
//			return ResultUtil.error(ResultEnum.Err_3042);
//		}
		PersonVo personVo=new PersonVo();
		personVo.setComId(user.getComId());
		personVo.setPId(user.getPId());
		personVo.setPPwd(pwd);

		Result result =  humanClientService.modifyPwd(personVo);
		//更新密码
		log.info("更新密码 -result【{}】",result);
		if(result.getCode()==200){
			Object from =  map.get("from");
			if(from==null){
				redisUtil.del("gzhToken:"+user.getComId()+":"+user.getPId());
			}
			return ResultUtil.success();
		}
		return ResultUtil.error(ResultEnum.Err_3014);
	}

	//是否弱密码
//	@PostMapping(WxServiceUrl.URL_isWeekPassword)
//	public Result isWeekPassword(@RequestBody Map<String,Object> map){
//		GzhUserInfo user = (GzhUserInfo) map.get("userInfo");
//
//		if(user.getComId()==null || user.getComId()<=0l
//		|| user.getPId() ==null || user.getPId()<=0l ){
//			return ResultUtil.success();
//		}
//
//		List<Long>  checkComId  =new ArrayList<>();
//		Collections.addAll(checkComId, 75l, 77l, 89l, 106l, 110l, 113l, 123l, 126l, 127l, 130l, 133l,
//				526l, 584l, 619l, 622l, 626l, 633l, 656l, 670l, 671l, 678l, 680l, 706l);
//
//		if(!checkComId.contains(user.getComId())){
//			return ResultUtil.success();
//		}
//		Result result =  humanClientService.GetPersonInfo(user.getComId(),user.getPId());
//		if (result.getCode()==200){
//			if (result.getData() !=null){
//				EntityPersonnelInfo entityPersonnelInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityPersonnelInfo.class);
//				if(!HandlePasswordUtil.isWeekPassword(entityPersonnelInfo.getPPwd())){
//					return ResultUtil.error(ResultEnum.Err_3107);
//				}
//			}
//		}
//		return ResultUtil.success();
//
//	}


	//修改头像
	@PostMapping(WxServiceUrl.URL_modifyPhoto)
	public Result modifyPhoho(MultipartFile file, String token
			, @RequestParam(value = "type",defaultValue = "1")Integer type){
		// 解析token
		GzhUserInfo userInfo = null;
		Gson gson = new Gson();
		try {
			String userStr  = RSAHelper.decipher(token, RsaConfig.privateKey);
			if(userStr == null){
				log.info("Pay-token异常 100 【{}】 ", token);
				return ResultUtil.error(ResultEnum.Err_3042);
			}
			userInfo = gson.fromJson(userStr,GzhUserInfo.class);
		} catch (Exception e) {
			log.info("Pay-token异常 2 【{}】 ", e);
			return ResultUtil.error(ResultEnum.Err_3042);
		}


		Object tokenRedis = redisUtil.get("gzhToken:" + userInfo.getComId()+":"+userInfo.getPId());
		if (tokenRedis == null) {
			return ResultUtil.error(ResultEnum.Err_4028);
		}

		//判断随机数是否一致
		GzhUserInfo userInfo1 = JSON.parseObject((String) tokenRedis,GzhUserInfo.class);

		if(!userInfo1.getLoginSecret().equals(userInfo.getLoginSecret())){
			return ResultUtil.error(ResultEnum.Err_4028);
		}

		//密码等级低
		if(!userInfo.getPasswordCorrect()){
			return ResultUtil.error(ResultEnum.Err_3050);
		}

		if(file==null){
			if(type == 1) return ResultUtil.error(ResultEnum.Err_3057);

			log.info("清空照片 【{}】",userInfo1);

			PersonVo personVo=new PersonVo();
			personVo.setComId(userInfo.getComId());
			personVo.setPId(userInfo.getPId());
			personVo.setPPhotoUrl2("");

			Result result1 = humanClientService.modifyPhoto(personVo);
			if(result1.getCode()!=200){
				return ResultUtil.error(ResultEnum.Err_3014);
			}

			SignatureUpdateRequest signatureUpdateRequest=new SignatureUpdateRequest();
			signatureUpdateRequest.setComId(userInfo.getComId());
			signatureUpdateRequest.setPId(userInfo.getPId());

			payConfigClientService.revokedSignRecords(signatureUpdateRequest);


			GetRepairPayRecordListRequest getRepairPayRecordListRequest = new GetRepairPayRecordListRequest();
			getRepairPayRecordListRequest.setComId(userInfo.getComId());
			getRepairPayRecordListRequest.setPId(userInfo.getPId());
			getRepairPayRecordListRequest.setStatus(0);
			Result<Map<Object, Object>> repairPayRecordList = payConfigClientService.getRepairPayRecordList(getRepairPayRecordListRequest);
			if(repairPayRecordList.getData().get("total")!=null && (Integer)(repairPayRecordList.getData().get("total"))==0){
				Result result24 = payConfigClientService.setXFWhiteInfo(userInfo.getComId(),userInfo.getPId(),0l);
				log.info("更新白名单返回1 -result【{}】",result24);
			}else{
				log.info("存在补缴 不更新白名单 -result【{}】",repairPayRecordList);
			}

			return ResultUtil.success();
		}

		String base646 = "";
		try {
			byte[] bytes = file.getBytes(); // 获取文件内容的字节数组
			base646 =  Base64Utils.encodeToString(bytes); // 将字节数组编码成 base64 字符串
		} catch (IOException e) {
			e.printStackTrace();
			return ResultUtil.error(ResultEnum.Err_4151);
		}

		String ytr = faceDetect(base646);
		BDFaceToken bdFaceToken = JSON.parseObject(ytr, BDFaceToken.class);

		log.info("百度算法返回 c4Xa8WOt 【{}】【{}】【{}】",ytr,bdFaceToken,file.getSize());

		if(bdFaceToken==null || (bdFaceToken.getErrorCode()!=0 && bdFaceToken.getErrorCode()!=18 && bdFaceToken.getErrorCode()!=17)){

//			Result result = minioClientService.upload(file);
			log.info("百度算法检测失败图片 I5nWycS7 【{}】 【{}】", userInfo, bdFaceToken);

			return ResultUtil.info(bdFaceToken.getErrorCode(),"图片检测失败");
		}


		if(bdFaceToken.getErrorCode()!=18 && bdFaceToken.getErrorCode()!=17) {

			if (bdFaceToken.getResult().getFaceList().size() > 1) {
				return ResultUtil.error(ResultEnum.Err_4137);
			}

			List<String> stringList = new ArrayList<>();
			Float faceProbability = Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getFaceProbability().toString());
			if (faceProbability != 1f) {
				stringList.add("人脸置信度不为1,当前:" + faceProbability);
			}
			String gsType = (String) bdFaceToken.getResult().getFaceList().get(0).getGlasses().get("type");
			if (!gsType.equals("none")) {
				stringList.add("检测戴眼镜不通过，当前:" + gsType);
			}

			Float rightEye = Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getEyeStatus().get("right_eye").toString());
			if (rightEye < 0.9f) {
				stringList.add("右眼闭合度检测不通过，当前:" + rightEye);
			}

			Float leftEye = Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getEyeStatus().get("left_eye").toString());
			if (leftEye < 0.9f) {
				stringList.add("左眼闭合度检测不通过，当前:" + leftEye);
			}
			String faceType = (String) bdFaceToken.getResult().getFaceList().get(0).getFaceType().get("type");
			if (!faceType.equals("human")) {
				stringList.add("人脸类型不通过，当前:" + faceType);
			}
			Float probability = Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getFaceType().get("probability").toString());
			if (probability < 0.7f) {
				stringList.add("人脸类型判断正确的置信度检测不通过，当前:" + probability);
			}
			Integer mask = (Integer) bdFaceToken.getResult().getFaceList().get(0).getMask().get("type");
			if (mask == 1) {
				stringList.add("口罩检测，当前检测到口罩");
			}
			//	objectMap.put("口罩置信度，范围0~1",bdFaceToken.getResult().getFaceList().get(0).getMask().get("probability"));
			Float pleftEye = Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getOcclusion().get("left_eye").toString());
			if (pleftEye > 0.2f) {
				stringList.add("左眼遮挡比例检测不通过，当前:" + pleftEye);
			}
			Float prightEye = Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getOcclusion().get("right_eye").toString());
			if (prightEye > 0.2f) {
				stringList.add("右眼遮挡比例检测不通过，当前:" + prightEye);
			}

			Float pnose = Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getOcclusion().get("nose").toString());
			if (pnose > 0.2f) {
				stringList.add("鼻子遮挡比例检测不通过，当前:" + pnose);
			}
			Float pmouth = Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getOcclusion().get("mouth").toString());
			if (pmouth > 0.2f) {
				stringList.add("嘴巴遮挡比例检测不通过，当前:" + pmouth);
			}
			Float pleftCheek = Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getOcclusion().get("left_cheek").toString());
			if (pleftCheek > 0.2f) {
				stringList.add("左脸颊遮挡比例检测不通过，当前:" + pleftCheek);
			}
			Float prightCheek = Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getOcclusion().get("right_cheek").toString());
			if (prightCheek > 0.2f) {
				stringList.add("右脸颊遮挡比例检测不通过，当前:" + prightCheek);
			}
			Float pchinContour = Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getOcclusion().get("chin_contour").toString());
			if (pchinContour > 0.2f) {
				stringList.add("下巴遮挡比例检测不通过，当前:" + pchinContour);
			}
			Float blur = Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getBlur().toString());
			if (blur > 0.2f) {
				stringList.add("人脸模糊程度检测不通过，当前:" + blur);
			}
			Float completeness = Float.parseFloat(bdFaceToken.getResult().getFaceList().get(0).getQuality().getCompleteness().toString());
			if (completeness != 1f) {
				stringList.add("人脸完整度检测不通过，当前:" + completeness);
			}

			Integer illumination = bdFaceToken.getResult().getFaceList().get(0).getQuality().getIllumination();
			if (illumination < 80 || illumination > 250) {
				stringList.add("光照程度检测不通过，当前:" + illumination);
			}

			if (stringList.size() > 0) {
				return ResultUtil.info(3333, "人脸质量检测不通过", stringList);
			}
		}

		Result result =null;
		try {
			result = minioClientService.upload(file);
		}catch (Exception e){
			log.info("人脸上传失败 MilePre2  minio异常 -result【{}】",e);
			return ResultUtil.error(ResultEnum.Err_3058);
		}

		if(result == null || result.getCode()!=200){
			return ResultUtil.error(ResultEnum.Err_3058);
		}
		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString( result.getData()));
//		updateUserFaceVo.setPPhotoUrl(jsonObject.getString("imageUrl"));


		Result<UserInfoYkmVo> userInfoYkmVoResult = humanClientService.getPersonInfo(userInfo.getComId(),userInfo.getPId());


		PersonVo personVo=new PersonVo();
		personVo.setComId(userInfo.getComId());
		personVo.setPId(userInfo.getPId());
		personVo.setPPhotoUrl2(jsonObject.getString("imageUrl"));

		if(userInfoYkmVoResult.getCode()==200 && CommonUtil.isNull(userInfoYkmVoResult.getData().getPPhotoUrl())){
			personVo.setPPhotoUrl(jsonObject.getString("imageUrl"));
		}

		Result result1 = humanClientService.modifyPhoto(personVo);
		if(result1.getCode()!=200){
			return ResultUtil.error(ResultEnum.Err_3014);
		}
//		FaceCheckRequest faceCheckRequest = new FaceCheckRequest();
//		faceCheckRequest.setUrl(jsonObject.getString("imageUrl"));
//		faceCheckRequest.setComId(userInfo.getComId());
//		faceCheckRequest.setPId(userInfo.getPId());
//		mqSimpleClientService.faceCheck(faceCheckRequest);


		//人脸特征值
		try {
			if (StringUtils.isNotBlank(personVo.getPPhotoUrl2())) {
				FeatureRequest featureRequest = new FeatureRequest();
				featureRequest.setComId(personVo.getComId());
				featureRequest.setPId(personVo.getPId());
				featureRequest.setUrl(null);
				featureRequest.setUrl2(personVo.getPPhotoUrl2());
				humanClientService.feature(featureRequest);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}


		GetRepairPayRecordListRequest getRepairPayRecordListRequest = new GetRepairPayRecordListRequest();
		getRepairPayRecordListRequest.setComId(userInfo.getComId());
		getRepairPayRecordListRequest.setPId(userInfo.getPId());
		getRepairPayRecordListRequest.setStatus(0);
		Result<Map<Object, Object>> repairPayRecordList = payConfigClientService.getRepairPayRecordList(getRepairPayRecordListRequest);
		if(repairPayRecordList.getData().get("total")!=null && (Integer)(repairPayRecordList.getData().get("total"))==0){

			Result result24 = payConfigClientService.setXFWhiteInfo(userInfo.getComId(),userInfo.getPId(),0l);
			log.info("更新白名单返回2 -result【{}】【{}】【{}】【{}】",userInfo.getPId(),userInfo.getOpenId(),personVo.getPPhotoUrl2(),result24);

			//判断门禁是否更新
			if(userInfoYkmVoResult.getCode()==200 && CommonUtil.isNull(userInfoYkmVoResult.getData().getPPhotoUrl())){
				Result<List<AccessListVo>> listResult = accessClientService.getAccessByUser(userInfo.getComId(),userInfo.getPId());
				if(listResult.getCode()==200 && listResult.getData()!=null && listResult.getData().size()>0){
					for (AccessListVo accessListVo:listResult.getData()){
						UserAccessPageSetAccessRequest userAccessPageSetAccessRequest=new UserAccessPageSetAccessRequest();
						userAccessPageSetAccessRequest.setCompanyId(userInfo.getComId());
						userAccessPageSetAccessRequest.setUserId(userInfo.getPId());
						userAccessPageSetAccessRequest.setPId(userInfo.getPId());
						userAccessPageSetAccessRequest.setRegionId(accessListVo.getRegionId());
						userAccessPageSetAccessRequest.setAreaNo(accessListVo.getAreaNo());
						userAccessPageSetAccessRequest.setRoleI(accessListVo.getRoleI());
						mqSimpleClientService.ChangeAccess(userAccessPageSetAccessRequest);
					}
				}
			}

		}else{
			log.info("存在补缴 不更新白名单 -result【{}】",repairPayRecordList);
		}

		return ResultUtil.success();
	}


	/**
	 * 添加学生
	 * @return
	 */
	@PostMapping(WxServiceUrl.Url_addPerson)
	public Result addPerson(@Valid @RequestBody AddPersonVo addPersonVo){

		//step 1 验证手机号
		Object code =  redisUtil.get("gzh:signCode:"+addPersonVo.getComId()+":"+addPersonVo.getPhone()+":" +addPersonVo.getCode());
		if(code == null){
			return ResultUtil.error(ResultEnum.Err_2002);
		}
		if(addPersonVo.getDeptId()==null){
			addPersonVo.setDeptId(0l);
		}

		PersonVo personVo =new PersonVo();
		personVo.setComId(addPersonVo.getComId());
		personVo.setDeptId(addPersonVo.getDeptId());
		personVo.setPPwd("000000");
		personVo.setPName(addPersonVo.getUsername());
		if(CommonUtil.isNull(addPersonVo.getUsername())){
			personVo.setPName(addPersonVo.getPhone());
		}
		personVo.setPCode(addPersonVo.getPhone());
		personVo.setPPhone(addPersonVo.getPhone());
		personVo.setStatus(0);

		//step 2 添加人员
		Result result = humanClientService.AddPerson(personVo);
		//添加人员返回
		log.info("result",result);
		if (result.getCode()!=200){
			return ResultUtil.error(result.getCode());
		}

		Integer accTypeId = 1  ;  //学生

		//添加消费账户
		EntityPersonnelInfo personnelInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityPersonnelInfo.class);

		EntityXfAccountInfo entityXfAccountInfo = new EntityXfAccountInfo();
		entityXfAccountInfo.setComId(addPersonVo.getComId());
		entityXfAccountInfo.setPId(personnelInfo.getPId());
		entityXfAccountInfo.setAccountNo(addPersonVo.getComId()+"P"+personnelInfo.getPId());
		entityXfAccountInfo.setAccountName(addPersonVo.getComId()+"P"+personnelInfo.getPId());
		entityXfAccountInfo.setAccountState(0);
		entityXfAccountInfo.setAccTypeId(accTypeId);

		Result result1 = payConfigClientService.AddXFAccount(entityXfAccountInfo);
		log.info("公众号添加消费账户 【{}】",result1);

		Map<String, Object> map1 = new HashMap<>();

		String appId ="wx4f9f6bd221934c14";
		String appSecret ="4b73282e981e116f0a80bace902ae17c";
		//TODO 获取appid 和 appSecret

		GzhUserInfo userInfo=new GzhUserInfo();

		String state = "";
		try {

			userInfo.setComId(addPersonVo.getComId());
			userInfo.setPId(personnelInfo.getPId());
			userInfo.setAppId(appId);
			userInfo.setAppSecret(appSecret);
			userInfo.setPPhone(addPersonVo.getPhone());
			userInfo.setPasswordCorrect(true);

			Gson gson =new Gson();
			String user = gson.toJson(userInfo);
			state = MD5.MD5Encode(addPersonVo.getComId()+"##"+personnelInfo.getPId(),"utf8");
			state = state.toUpperCase(Locale.ROOT);
			redisUtil.set("gzhMd5:"+state, user,120l);

			log.info("生成Token", user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		map1.put("state", state);
		map1.put("appId", appId);
		map1.put("passwordCorrect", true);
		return ResultUtil.success(map1);
	}


	public static String getAuth() {
		// 官网获取的 API Key 更新为你注册的
		String clientId = "ZfedCGbL7ZKR6ILKyOQGzOKF";
		// 官网获取的 Secret Key 更新为你注册的
		String clientSecret = "LPj7mTe9vdEbqKdwagrI3EBVjGodFMw9";
		return getAuth(clientId, clientSecret);
	}

	/**
	 * 获取API访问token
	 * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
	 *
	 * @param ak - 百度云官网获取的 API Key
	 * @param sk - 百度云官网获取的 Securet Key
	 * @return assess_token 示例：
	 * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
	 */
	public static String getAuth(String ak, String sk) {
		// 获取token地址
		String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
		String getAccessTokenUrl = authHost
				// 1. grant_type为固定参数
				+ "grant_type=client_credentials"
				// 2. 官网获取的 API Key
				+ "&client_id=" + ak
				// 3. 官网获取的 Secret Key
				+ "&client_secret=" + sk;
		try {
			URL realUrl = new URL(getAccessTokenUrl);
			// 打开和URL之间的连接
			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.err.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String result = "";
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			/**
			 * 返回结果示例
			 */
			System.err.println("result:" + result);
			org.springframework.boot.configurationprocessor.json.JSONObject jsonObject = new org.springframework.boot.configurationprocessor.json.JSONObject(result);
			String access_token = jsonObject.getString("access_token");
			return access_token;
		} catch (Exception e) {
			System.err.printf("获取token失败！");
			e.printStackTrace(System.err);
		}
		return null;
	}


	/**
	 * 重要提示代码中所需工具类
	 * FileUtil,Base64Util,HttpUtil,GsonUtils请从
	 * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
	 * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
	 * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
	 * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
	 * 下载
	 */
	public static String faceDetect(String base64) {
		// 请求url
		String url = "https://aip.baidubce.com/rest/2.0/face/v3/detect";
		try {
			Map<String, Object> map = new HashMap<>();
			map.put("image", base64);
			map.put("image_type", "BASE64");
			map.put("face_field", "age,expression,face_shape,gender,glasses,quality,eye_status,emotion,face_type,mask,spoofing");


			String param = GsonUtils.toJson(map);

			// 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
			String accessToken = getAuth();

			String result = HttpUtil.post(url, accessToken, "application/json", param);
			System.out.println(result);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	

}
